const app = getApp();
const db = wx.cloud.database()
import {
    subscribeLotteryMessage
  } from '../../api/subscribe.js'
  
Page({
    data: {
        userRecordl: false,
        userRecord: false,
        gameModel: "",
        sevenRecords: [],
        time: 15,
        view: "等待开奖",
        id:'',
        loading: true,
         userInfo:''
    },
    onLoad: function (e) {
        let that = this
        console.log(e)
        if (e.id == undefined) {
            wx.showToast({
                title: '缺少参数',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if(e.op){
            this.setData({
                op: e.op,
            })
        }
         this.setData({
id:e.id
         })
        //普通获取数据------------
        db.collection("active_list")
            .where({
                _id: e.id
            })
            .get()
            .then(res => {
                if (res.data.length > 0) {
                    that.setData({
                        gameModel: res.data[0],
                        HJXY: res.data[0].HJXY,
                        _id: res.data[0]._id,                  
                    })
                    //判断是否开奖
                    if (res.data[0].HJXY == true) {
                        that.setData({
                            HJ: res.data[0].HJ,
                            userRecord: true,
                            view: "已开奖",
                            loading:false
                        })
                        that.drawb() //展示参与人数
                        that.HJTC()  //获奖弹窗

                        return
                    }
                    else{
                      
                        if (that.data.gameModel.draw_count == that.data.gameModel.total_count) {
                            wx.showLoading({
                                title: '开奖中',
                            })
                            that.drawd()
                        }
                    }
                 
                    let p1 = new Promise((resolve, reject) => {
                        let that = this
                        wx.cloud.database()
                            .collection("game").where({
                                gameXY: that.data.gameModel._id
                            })
                            .get()
                            .then(res => {
                                resolve('p1')
                                console.log('参与人--length', res.data.length)
                                if (res.data.length > 0) {
                                    that.setData({
                                        sevenRecords: res.data,                           
                                    })
                                }                     
                                if (that.data.gameModel.HJXY == true) {
                                    return
                                }                 
                            })
                      })
                      let p2 = new Promise((resolve, reject) => {
                        let that = this
                        wx.cloud.callFunction({
                            name: 'openid'
                        }).then(res => {        
                            console.log('openid')       
                            that.setData({
                                openid: res.result.openid
                            })
                            //查看是否存在user
                            db.collection('user').where({
                                _openid:that.data.openid
                            }).get().then(res=>{
                               if(res.data.length>0){  
                                   console.log(res)
                                   this.setData({
                                      userInfo:res.data[0] 
                                   })
                                //存在user判断是否参加过此活动
                                db.collection("game").where({
                                    _id: that.data.gameModel._id + that.data.openid
                                })
                                .get()
                                .then(res => {
                                    resolve('p1')
                                  
                                    console.log('game-length', res.data.length)
                                    if (res.data.length > 0) {
                                        that.setData({
                                            userRecord: true//判断参将按钮
                                        })
                                    }
                                   
                                })//判断此人是否以参加
                               }
                               else{
                                resolve('p1')
                               }
                            })
                      
                        }).catch(err => {
                            console.log(err)
                        })
                      })
                      // 等p1/p2执行完
                       Promise.all([p1, p2,]).then(res => {
                        console.log('全部完成')
                        console.log(res)
                      
                        this.setData({
                            loading:false
                        })
                        
                      }).catch(err => {
                         console.log('失败')
                         console.log(err)
                      })
                    
                } else {
                    wx.showToast({
                        title: '活动已结束',
                        icon: 'none',
                        duration: 50000
                    })
                }
           
            })
    },
    //获取openid------------
    openid: function () {
        let that = this
        wx.cloud.callFunction({
            name: 'openid'
        }).then(res => {
            that.setData({
                openid: res.result.openid
            })  
            that.drawa()//判断此人是否以参加
        }).catch(err => {
            console.log(err)
        })
    },
     
    //订阅信息参与抽奖
    draw: function () {
        let that = this
  
        // 如果不存在user则调取哟用户信息
 if(!that.data.userInfo)
        {
            let a='XluuEpi_zp7E5kVYrxd759Rb7D9ws9nOQRoiAxNQTvE'
            wx.requestSubscribeMessage({
                tmplIds: [
                   a
                ],
                success(res) {
                    console.log("订阅消息API调用成功：", res)
                },
                fail(res) {
                    console.log("订阅消息API调用失败：", res)
                }
            }) 
            wx.getUserProfile({
          desc: '用于完善会员资料',
          success: (res) => {
              console.log(res.userInfo)
              let userInfo=res.userInfo
              wx.cloud.database().collection('game').add({
                data: {
                    avatarUrl: res.userInfo.avatarUrl,
                    nickName: res.userInfo.nickName,
                    items: that.data.gameModel.items,
                    creater_info: that.data.gameModel.creater_info,
                    name: that.data.gameModel.name,
                    draw_count: that.data.gameModel.draw_count,
                    _id: that.data.gameModel._id + that.data.openid, //参与活动id
                    gameXY: that.data.gameModel._id //抽奖活动id
                },
                success(res) {
                    console.log('addugame')
                    wx.showToast({
                        title: '参与成功',
                        icon: 'success',
                        duration: 1000
                    })
                    console.log('新增game', res)
                    wx.cloud.database().collection('user').add({
                        data: {
                            avatarUrl: userInfo.avatarUrl,
                            nickName: userInfo.nickName,    
                            jifen:100,
                            qiandaotype:false ,
                            luckNum:10
                        },
                        success(res) {        
                          console.log('adduser')                
                        },
                        fail(res) {
                            console.log('新增user', res)
                        }
                    })
                    that.drawa()
                    that.drawb()
                    that.drawc()
                    if (that.data.gameModel.draw_count == that.data.gameModel.total_count+1) {
                        wx.showLoading({
                            title: '开奖中',
                        })
                        that.drawd()
                    }
                },
                fail(res) {
                    console.log('新增hf', res)
                }

            })   
        
          }
      })
}
      else
{
    let a='XluuEpi_zp7E5kVYrxd759Rb7D9ws9nOQRoiAxNQTvE'
    wx.requestSubscribeMessage({
        tmplIds: [
           a
        ],
        success(res) {
            console.log("订阅消息API调用成功：", res)
        },
        fail(res) {
            console.log("订阅消息API调用失败：", res)
        }
    })
                wx.cloud.database().collection('game').add({
                    data: {
                        avatarUrl: that.data.userInfo.avatarUrl,
                        nickName: that.data.userInfo.nickName,
                        items: that.data.gameModel.items,
                        creater_info: that.data.gameModel.creater_info,
                        name: that.data.gameModel.name,
                        draw_count: that.data.gameModel.draw_count,
                        _id: that.data.gameModel._id + that.data.openid, //参与活动id
                        gameXY: that.data.gameModel._id //抽奖活动id
                    },
                    success(res) {
                        wx.showToast({
                            title: '参与成功',
                            icon: 'success',
                            duration: 1000
                        })
                        console.log('新增game', res)
                        
                        that.drawa()
                        that.drawb()
                        that.drawc()

                        if (that.data.gameModel.draw_count == that.data.gameModel.total_count+1) {
                            wx.showLoading({
                                title: '开奖中',
                            })
                            that.drawd()
                        }
                    },
                    fail(res) {
                        console.log('新增hf', res)
                    }

                })
          }
       
    },
    //判断当前参与人信息是否参加
    drawa: function () {
        let that = this
        db.collection("game").where({
                _id: that.data.gameModel._id + that.data.openid
            })
            .get()
            .then(res => {
                this.setData({
                    userRecordl: true
                })
                console.log('game-length', res.data.length)
                if (res.data.length > 0) {
                    that.setData({
                        userRecord: true//判断参将按钮
                    })
                }
               
            })
    },
    //展示参与人信息
    drawb: function () {
        console.log('b')
        let that = this
        wx.cloud.database()
            .collection("game").where({
                gameXY: that.data.gameModel._id
            })
            .get()
            .then(res => {     
                console.log('参与人--length', res.data.length)
                if (res.data.length > 0) {
                    that.setData({
                        sevenRecords: res.data,
                        
                    })
                }
                if (that.data.gameModel.HJXY == true) {
                    return
                }
                 if (that.data.gameModel.draw_count == that.data.gameModel.total_count) {
                    wx.showLoading({
                        title: '开奖中',
                    })
                    that.drawd()
                }
            })
    },
    //存获奖信息 //修改参与人数
    drawc: function () {
        let that=this
        wx.cloud.callFunction({
            name: 'update',
            data: {
                action:'join-count',
                _id: this.data.gameModel._id
            }
        }).then(res => {
            db.collection("active_list")
            .where({
                _id: that.data.id
            })
            .get()
            .then(res => {
                if(res.data.length>0)
{this.setData({
    gameModel:res.data[0]
})}
            })
            console.log("drawc", res)
        }).catch(err => {
            console.log(err)
        })
    },
    //获取开奖
    drawd: function () {
        let that = this
        if(that.data.gameModel.control=='是'){
            wx.cloud.database().collection('game')
            .aggregate()
            .match({
                gameXY: that.data.gameModel._id,
                control:'是'

            })
            .sample({
                size: parseInt(that.data.gameModel.items[0].count)
            })
            .end().then(res => {
                console.log(res.list)
                wx.cloud.callFunction({
                    name: 'update',
                    data: {
                        action: "get-price",
                        _id: res.list[0].gameXY,
                        list: res.list
                    }
                }).then(res => {
                    setTimeout(function () {
                        wx.hideLoading()
                    }, 2000)
                    if (res.result.stats.updated == 1) {
                        wx.cloud.database() //普通获取数据------------
                            .collection("active_list")
                            .where({
                                _id: that.data._id
                            })
                            .get()
                            .then(res => {
                                console.log('获取成功', res)
                                if (res.data.length > 0) {
                                    that.setData({
                                        gameModel: res.data[0],
                                        HJ: res.data[0].HJ,
                                        view: "已开奖"
                                    })
                                    that.HJTC()
                                    that.FSDY()
                                } else {
                                    wx.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        duration: 2000
                                    })
                                }
                                wx.hideLoading()
                            })
                    }
                }).catch(err => {
                    console.log(err)
                })

            })
        }
        else
  {      wx.cloud.database().collection('game')
            .aggregate()
            .match({
                gameXY: that.data.gameModel._id
            })
            .sample({
                size: parseInt(that.data.gameModel.items[0].count)
            })
            .end().then(res => {
                console.log(res.list)
                wx.cloud.callFunction({
                    name: 'update',
                    data: {
                        action: "get-price",
                        _id: res.list[0].gameXY,
                        list: res.list
                    }
                }).then(res => {
                    setTimeout(function () {
                        wx.hideLoading()
                    }, 2000)
                    if (res.result.stats.updated == 1) {
                        wx.cloud.database() //普通获取数据------------
                            .collection("active_list")
                            .where({
                                _id: that.data._id
                            })
                            .get()
                            .then(res => {
                                console.log('获取成功', res)
                                if (res.data.length > 0) {
                                    that.setData({
                                        gameModel: res.data[0],
                                        HJ: res.data[0].HJ,
                                        view: "已开奖"
                                    })
                                    that.HJTC()
                                    that.FSDY()
                                } else {
                                    wx.showToast({
                                        title: '网络错误',
                                        icon: 'none',
                                        duration: 2000
                                    })
                                }
                                wx.hideLoading()
                            })
                    }
                }).catch(err => {
                    console.log(err)
                })

            })}
    },
    //获奖弹窗
    HJTC: function () {
        let that = this
        let HJ = that.data.HJ//获奖人信息
        console.log("获奖弹窗", HJ)
        wx.showModal({
            title: '已开奖',
            content: '幸运用户' + HJ[0].nickName,
            success(res) {
                if (res.confirm) {

                    console.log('用户点击确定')
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },  
    //发送订阅
    FSDY() {
        console.log('发送订阅')
        let that = this
        const db = wx.cloud.database()
        db.collection('game').aggregate()
            .match({
                gameXY: that.data.gameModel._id
            })
            .limit(1000)
            .end()
            .then(res => {
                let FSDYlist = res.list
                console.log(that.data.gameModel)
                for (var i = 0; i < FSDYlist.length; i++) {
                    wx.cloud.callFunction({ //获取openid------------
                        name: 'setmsg',
                        data: {
                            action:'抽奖结果通知',
                            openapi: FSDYlist[i]._openid,
                            page: "pages/active_detail/game?id=" + that.data.gameModel._id,
                            name: that.data.gameModel.name,
                            
                        }
                    }).then(res => {
                        console.log("发送订阅", res)
                    }).catch(err => {
                        console.log(err)
                    })
                }
            })
    },
    //回到首页
    SY: function () {
        wx.reLaunch({
            url: '/pages/index/index',
        })
    },
    //推广
    TG() {
        let that = this
        let op = this.data.op
        if (op) {
            console.log(op, "一级推广op")
            wx.cloud.database() //一级推广
                .collection("user")
                .where({
                    _id: op
                })
                .get()
                .then(res => {
                    console.log("一级推广list", res.data[0])
                    wx.cloud.callFunction({ //存获奖信息 //修改参与人数
                        name: 'list',
                        data: {
                            if: "TG1",
                            _id: op
                        }
                    }).then(res => {
                        console.log(res.result.stats.updated, "一级推广修改")
                    }).catch(err => {
                        console.log(err)
                    })
                    if (res.data[0].TGOP) {
                        console.log(op, "二级推广op")
                        wx.cloud.database() //一级推广
                            .collection("user")
                            .where({
                                _id: res.data[0].TGOP
                            })
                            .get()
                            .then(res => {
                                console.log("二级推广list", res.data[0])
                                wx.cloud.callFunction({ //存获奖信息 //修改参与人数
                                    name: 'list',
                                    data: {
                                        if: "TG2",
                                        _id: res.data[0]._id
                                    }
                                }).then(res => {
                                    console.log(res.result.stats.updated, "二级推广修改")
                                }).catch(err => {
                                    console.log(err)
                                })
                            })
                    }
                })
        }
    },
    //分享功能
    onShareAppMessage: function () {
        return {
            title: "我的抽奖：" + this.data.gameModel.name,
            imageUrl: this.data.gameModel.items[0].image,
            path: "/pages/active_detail/game?id=" + this.data.gameModel._id + "&op=" + this.data.openid
        };
    },
    //复制微信号
    CopyLink(e) {
        wx.setClipboardData({
            data: e.currentTarget.dataset.link,
            success: res => {
                wx.showToast({
                    title: '已复制',
                    duration: 1000,
                })
            }
        })
    },
    //浏览图片
    previewImage: function (e) {
        wx.previewImage({
            urls: e.currentTarget.dataset.image,
            current: e.currentTarget.dataset.image[0]
        })
    },
     // 预览图片
     previewImg: function (e) {
        let imgData = e.currentTarget.dataset.img;
        wx.previewImage({
          //当前显示图片
          current: imgData[0],
          //所有图片
         urls:[ imgData]
        })
      },
});